package com.ailight.smart.gateway.util;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.stereotype.Component;

import java.security.KeyPair;
import java.time.Duration;
import java.util.Date;

/**
 * @author: 朱海鹏
 * @Package: com.ailight.smart.gateway.util
 * @Project: ai-light
 * @date: 2025/3/21 16:49
 * @description : jwt登录
 */
@Component
public class JwtUtil {
    private final JWTSigner jwtSigner;

    public JwtUtil(KeyPair keyPair) {
        this.jwtSigner = JWTSignerUtil.createSigner("rs256", keyPair);
    }

    /**
     * 创建 access-token
     *
     * @param userId 用户Id
     * @param ttl    时间差
     * @return 结果 token
     */
    public String createToken(Long userId, Duration ttl) {
        return JWT.create()
                .setPayload("user", userId)
                .setExpiresAt(new Date(System.currentTimeMillis() + ttl.toMillis()))
                .setSigner(jwtSigner)
                .sign();

    }

    public Long parseToken(String token) {
        // 1.校验token是否为kong
        if (StrUtil.isBlank(token)) {
            throw new RuntimeException("无效的token");
        }
        JWT jwt;
        try {
            jwt = JWT.of(token).setSigner(jwtSigner);
        } catch (Exception e) {
            throw new RuntimeException("无效的token");
        }
        // 校验token 是否有效
        if (jwt.verify()){
            // 验证失败
            throw new RuntimeException("无效的token");
        }
        // 验证token是否已经过期
        try {
            JWTValidator.of(jwt).validateDate();
        } catch (ValidateException e) {
            throw new RuntimeException("token已经过期");
        }
        // 4.数据格式校验
        Object userPayload = jwt.getPayload("user");
        if (userPayload == null) {
            // 数据为空
            throw new RuntimeException("无效的token");
        }

        // 5.数据解析
        try {
            return Long.valueOf(userPayload.toString());
        } catch (RuntimeException e) {
            // 数据格式有误
            throw new RuntimeException("无效的token");
        }
    }
}
